﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MRBrowserLibrary
{
    public class PageEvent
    {
        private WebBrowser webBrowser;
        private Dictionary<String, List<EventElement>> eventHandlerDictionary;

        public PageEvent(WebBrowser webBrowser)
        {
            this.webBrowser = webBrowser;
            eventHandlerDictionary = new Dictionary<string, List<EventElement>>();
        }

        public void AddEvent(string url, string id, HtmlElementEventHandler handler)
        {
            string key = string.Empty;
            if (url.Contains("/"))
            {
                key = url.Substring(url.LastIndexOf("/") + 1);
            }
            else
            {
                key = url;
            }
            EventElement element = new EventElement(webBrowser, id, handler, false);
            if (eventHandlerDictionary.ContainsKey(key))
            {
                eventHandlerDictionary[key].Add(element);
            }
            else
            {
                List<EventElement> list = new List<EventElement>();
                list.Add(element);
                eventHandlerDictionary.Add(key, list);
            }
        }

        public void BindPage()
        {
            if (webBrowser != null && webBrowser.Url != null)
            {
                string url = webBrowser.Url.AbsoluteUri;
                string key = string.Empty;
                if (url.Contains("/"))
                {
                    key = url.Substring(url.LastIndexOf("/") + 1);
                }
                else
                {
                    key = url;
                }
                if (!string.IsNullOrEmpty(url))
                {
                    if (eventHandlerDictionary != null && eventHandlerDictionary.ContainsKey(key))
                    {
                        List<EventElement> eventElements = eventHandlerDictionary[key];
                        foreach (var eventElement in eventElements)
                        {
                            eventElement.Bind();
                        }
                    }
                }
                if (eventHandlerDictionary != null && eventHandlerDictionary.ContainsKey("*"))
                {
                    List<EventElement> eventElements = eventHandlerDictionary["*"];
                    foreach (var eventElement in eventElements)
                    {
                        eventElement.Bind();
                    }
                }
                
            }
        }
    }
}
